package com.spring.arch.uaa.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.spring.arch.common.idgenerator.IdGenerator;
import com.spring.arch.uaa.enums.OrganizationType;
import com.spring.arch.common.idgenerator.IdGenerator;
import com.spring.arch.uaa.enums.OrganizationType;
import com.spring.arch.uaa.model.Organization;
import com.spring.arch.uaa.model.OrganizationEmployee;
import com.spring.arch.uaa.model.Tenant;
import com.spring.arch.uaa.model.TenantEmployee;
import com.spring.arch.uaa.repository.OrganizationEmployeeRepository;
import com.spring.arch.uaa.repository.OrganizationRepository;
import com.spring.arch.uaa.repository.TenantEmployeeRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author: nandy
 * @createDate: 2019/11/4 17:19
 * @description:
 */
public class OrganizationListener extends AnalysisEventListener<OrganizationExportBean> {

    List<OrganizationExportBean> list = new ArrayList<>();

    private TenantEmployeeRepository tenantEmployeeRepository;

    private OrganizationRepository organizationRepository;

    private OrganizationEmployeeRepository organizationEmployeeRepository;

    private Tenant tenant;

    public OrganizationListener(TenantEmployeeRepository tenantEmployeeRepository,
                                OrganizationRepository organizationRepository,
                                OrganizationEmployeeRepository organizationEmployeeRepository, Tenant tenant) {
        this.tenantEmployeeRepository = tenantEmployeeRepository;
        this.organizationRepository = organizationRepository;
        this.tenant = tenant;
        this.organizationEmployeeRepository = organizationEmployeeRepository;
    }

    public List<OrganizationExportBean> getList() {
        return list;
    }

    @Transactional
    @Override
    public void invoke(OrganizationExportBean data, AnalysisContext analysisContext) {

        Optional<TenantEmployee> tenantEmployee = tenantEmployeeRepository.findByCodeAndTenantId(data.getCode(),
                tenant.getId());

        Optional<Organization> organizationOptional = organizationRepository.findByNameAndTenantAndDisableFalse(data.getOrganization(),
                tenant);

        String[] departmentArray = data.getDepartment().split("-");

        boolean flag = true;

        if(StringUtils.isBlank(data.getCode())) {

            data.setResult("失败");
            data.setReason("工号不能为空");

        } else if(StringUtils.isBlank(data.getOrganization())) {

            data.setResult("失败");
            data.setReason("组织机构不能为空");

        } else if(StringUtils.isBlank(data.getDepartment())) {

            data.setResult("失败");
            data.setReason("部门不能为空");

        } else if(!tenantEmployee.isPresent()) {

            data.setResult("失败");
            data.setReason("找不到该人员信息");

        } else if(!organizationOptional.isPresent()) {

            data.setResult("失败");
            data.setReason("找不到该组织机构");

        } else if(departmentArray.length > 0) {

            try {

                for(int i = 1; i < departmentArray.length; i++) {

                    Optional<Organization> departmentOptional =
                            organizationRepository.findByNameAndTenantAndDisableFalse(departmentArray[i], tenant);

                    Organization department = departmentOptional.get();

                    if(!departmentOptional.isPresent()) {

                        Organization model = new Organization();
                        model.setParent(organizationOptional.get());

                        model.setTenant(model.getParent().getTenant());
                        model.setProject(model.getParent().getProject());

                        model.setCode(IdGenerator.uniqueCode());
                        model.setName(departmentArray[i]);
                        model.setType(OrganizationType.FUNCTION);

                        department = organizationRepository.save(model);
                    }

                    if(i == departmentArray.length - 1) {

                        OrganizationEmployee organizationEmployee = new OrganizationEmployee();

                        organizationEmployee.setOrganization(department);
                        organizationEmployee.setEmployee(tenantEmployee.get());

                        organizationEmployeeRepository.save(organizationEmployee);
                    }
                }

                data.setResult("成功");

            } catch(Exception e) {

                data.setResult("失败");
                data.setReason("未知原因，请联系管理员");
            }
        }

        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}
